from . import user_blue
from flask import render_template,jsonify,current_app,redirect,url_for,g,request,session
from info.utils.response_code import RET
from info.models import House,Area
from info import db,constants
from info.utils.commons import login_required
from info.utils.image_storage import storage
import re
from info.models import User

#个人中心
@user_blue.route('/api/v1.0/user')
@login_required
def base_user():
    #返回avatar_url,mobile,name
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    data = user.to_dict()
    return jsonify(errno=RET.OK,errmsg='OK',data=data)

#修改用户名
@user_blue.route('/api/v1.0/user/name',methods=['POST'])
@login_required
def change_name():
    #接收参数
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    #修改用户名，获取参数
    user_new_name = request.json.get('name')
    if not user_new_name:
        return jsonify(errno=RET.NODATA,errmsg='没有数据')
    user.name = user_new_name
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='保存数据失败')
    session['name'] = user_new_name
    return jsonify(errno=RET.OK,errmsg='OK')

#修改头像
@user_blue.route('/api/v1.0/user/avatar',methods=['POST'])
@login_required
def change_img_url():

    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    #获取图像
    avatar = request.files.get('avatar')
    # 判断参数是否存在
    if not avatar:
        return jsonify(errno=RET.PARAMERR, errmsg='参数不存在')
    # 读取图片文件
    try:
        image_data = avatar.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='读取图片数据失败')
    # 把读取后的图片的数据，传入七牛云
    try:
        image_name = storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='上传图片异常')
    # 保存图片数据
    user.avatar_url = image_name
    # 提交数据
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存数据失败')
    # 拼接图片的绝对路径，返回前端
    avatar_url = constants.QINIU_DOMIN_PREFIX + image_name
    data = {
        'avatar_url': avatar_url
    }
    # 返回结果
    return jsonify(errno=RET.OK, errmsg='OK', data=data)


#用户实名认证
@user_blue.route('/api/v1.0/user/auth',methods=['GET','POST'])
@login_required
def user_fact():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    if request.method == 'GET':
        data = user.to_auth_info()
        return jsonify(errno=RET.OK,errmsg='OK',data=data)

    real_name = request.json.get('real_name')
    id_card = request.json.get('id_card')

    if not all([real_name,id_card]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数不完整')
    if not re.match(r'^[1-9][0-7]\d{4}((19\d{2}(0[13-9]|1[012])(0[1-9]|[12]\d|30))|(19\d{2}(0[13578]|1[02])31)|(19\d{2}02(0[1-9]|1\d|2[0-8]))|(19([13579][26]|[2468][048]|0[48])0229))\d{3}(\d|X|x)?$', id_card):
        return jsonify(errno=RET.PARAMERR,errmsg='身份证格式错误')
    if not re.match(r'^\s*[\u4e00-\u9fa5]{1,}[\u4e00-\u9fa5.·]{0,15}[\u4e00-\u9fa5]{1,}\s*$',real_name):
        return jsonify(errno=RET.PARAMERR,errmsg='身份证姓名')
    try:
        is_already = user.query.filter(User.id_card==id_card).count()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询错误')
    if is_already != 0 :
        return jsonify(errno=RET.PARAMERR,errmsg='身份证已经被注册')

    user.real_name=real_name
    user.id_card=id_card
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='保存数据失败')
    return jsonify(errno=RET.OK,errmsg='OK')

#我的房屋发布
@user_blue.route('/api/v1.0/user/houses')
@login_required
def my_houses():
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg='用户未登录')
    try:
        house_data = House.query.filter(House.user_id==user.id).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg='查询房屋错误')
    data = []
    if house_data:
        for item in house_data:
            data.append(item.to_basic_dict())
    return jsonify(errno=RET.OK,errmsg='OK',data=data)


